﻿using SearchForWorkitemsChanges.ExternalActions.ExportRdlcComponents;
using SearchForWorkitemsChanges.ExternalActions.ExportXmlComponents;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SearchForWorkitemsChanges.ExternalActions
{
    /// <summary>
    /// This class is a implementing class of <see cref="IExternalAction"/> for the reporting plugin.
    /// </summary>
    /// <remarks>
    /// The assembly embeds a default report. On report plugin's call, a copy of the default report is done in the application folder (if no report named WorkItemReport.rdlc is found, and if user security granted the copy).<br/>
    /// User can modify this copy to change the template with Microsoft Visual Studio.<br/>
    /// The most important things are : do not change the DataSourceName and DataSource Type !<br />
    /// Once done, you will have to add / modify the AppSetting named ExportRdlc_ReportPath with the report's name (or the absolute path to the report).
    /// </remarks>
    internal class ExportRdlc : IExternalAction
    {
        /// <summary>
        /// Name displayed on the button
        /// </summary>
        public string DisplayName
        {
            get { return "Reporting"; }
        }

        /// <summary>
        /// ToolTip displayed on the button
        /// </summary>
        public string TooltipDescription
        {
            get { return "Create a report that allow you to export a xls, rtf or pdf file"; }
        }

        /// <summary>
        /// Execute called on button click
        /// </summary>
        /// <param name="workitems">The search result</param>
        public void Execute(IEnumerable<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem> workitems)
        {
            var items = new List<SerializedFacadeWorkItem>();
            foreach (var itemSrc in workitems)
                items.Add(new SerializedFacadeWorkItem(itemSrc));

            try
            {
                ExtractRdlcIfNeeded();
            }
            catch (Exception exc)
            {
                MessageBox.Show("Could not copy report template into application path. Report will be construct with the embedded template. Error : " + exc.Message);
            }

            new WinReportViewer(ConfigurationManager.AppSettings["ExportRdlc_ReportPath"], items).ShowDialog();
        }

        private void ExtractRdlcIfNeeded()
        {
            var appPath = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName).Directory.FullName;
            var filePath = Path.Combine(appPath, "WorkItemReport.rdlc");
            if (!File.Exists(filePath))
            {
                using (Stream input = typeof(ExportRdlc).Assembly.GetManifestResourceStream(WinReportViewer.RdlcReportUsed))
                using (Stream output = File.Create(filePath))
                {
                    CopyStream(input, output);
                }
            }
        }

        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[8192];

            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
    }
}
